package com.zizo.autohome.tfidf;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.zizo.util.ConnectionPool;

/**
 * @ClassName: UpdateVal
 * @Description: 更新最后的TF-IDF值
 * @author HeYan
 * @date 2016年12月21日 上午10:08:33
 *
 */
public class UpdateVal implements Runnable {
	private Connection conn;
	private String tablename;

	public UpdateVal(Connection conn, String tablename) {
		super();
		this.conn = conn;
		this.tablename = tablename;
	}

	/**
	 * @Title: getAllTable
	 * @Description: 得到所有TF-IDF的表名称，已做更新
	 * @return
	 * @return List<String>
	 * @author Alexis
	 */
	public List<String> getAllTable() {
		List<String> list = new ArrayList<String>();
		Statement st = null;
		ResultSet rs = null;
		String sql = "SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA='TF-IDF' AND TABLE_NAME LIKE 'tf_idf_%'";
		try {
			st = conn.createStatement();
			rs = st.executeQuery(sql);
			while (rs.next()) {
				list.add(rs.getString(1));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}

	public void run() {
		PreparedStatement ps = null;
		String sql = "update " + tablename
				+ " AS a JOIN (SELECT word,idf FROM idf) AS b ON a.word=b.word SET a.val=a.tf*b.idf";
		try {
			ps = conn.prepareStatement(sql);
			ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				ps.close();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		System.out.println(tablename);
	}

	public static void main(String[] args) {
		long start = System.currentTimeMillis();
		ExecutorService fix = Executors.newFixedThreadPool(20);
		Connection conn = ConnectionPool.getConnection("TF-IDF", "localhost");
		UpdateVal val = new UpdateVal(conn, "");
		List<String> tablenames = val.getAllTable();
		for (String s : tablenames) {
			fix.execute(new UpdateVal(conn, s));
		}
		fix.shutdown();
		while (true) {
			if (fix.isTerminated()) {
				System.out.println("用时:" + (System.currentTimeMillis() - start) / (1000 * 60) + "min");
			} else {
				try {
					Thread.sleep(1000 * 60);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
